<?php

require_once WACT_ROOT . 'controller/controller.inc.php';
require_once WACT_ROOT . 'controller/form.inc.php';
require_once WACT_ROOT . 'validation/rules/match.inc.php';
require_once WACT_ROOT . 'validation/rules/member.inc.php';
require_once WACT_ROOT . 'validation/rules/pattern.inc.php';
require_once APP_ROOT . 'model/common/event.php';
require_once APP_ROOT . 'model/common/date.php';
require_once APP_ROOT . 'model/common/categories.php';
require_once APP_ROOT . 'model/common/session.php';
require_once APP_ROOT . 'model/common/form.php';
require_once APP_ROOT.'include/inc.config.php';


// article create/update form
class EventFormController extends FormController {

	var $admin_user = false;
	var $staff_user = false;
	var $view; // current view

	function setUserType($admin_user=false, $staff_user = false) {
		$this->admin_user = $admin_user;
        $this->staff_user = $staff_user;
	}

    function setView(&$view) {
    	$this->view = $view;
    }


	 function EventFormController() {
     	$this->addChild('create', new ButtonController(new Delegate($this, 'create'))); // create
        $this->addChild('save', new ButtonController(new Delegate($this, 'save'))); // save
        $this->addChild('delete', new ButtonController(new Delegate($this, 'delete'))); // delete

        $this->addChild('clean', new ButtonController(new Delegate($this, 'clean'))); // clean
        $this->addChild('events', new ButtonController(new Delegate($this, 'back'))); // clean

        $this->setDefaultChild('clean');

        // validation
		$this->addRule(new Handle('RequiredRule', array('title')));
        $this->addRule(new Handle('SizeRangeRule', array('title', 64)));


        $this->registerOnLoadListener(new Delegate($this, 'load'));
        //$this->registerOnActivateListener(new Delegate($this, 'check'));

        $this->addView('delete', new Handle('RedirectView', array('/delete')));

	 }

	 function makeDate(&$responseModel, $date_str, $target_field) {
            //prepare date
            list($day,$month,$year) = explode('/', $date_str);

            if ($day>0 && $month>0 && $year>2000) {
            	$mydate = gmmktime(0,0,0, $month,$day,$year);
                //$tz =& new MyTimeZone();
            	//$mydate = $tz->timeLocal($mydate);
                $responseModel->set($target_field,gmdate("Y-m-d",$mydate));
            }
            //print date("Y-m-d",$mydate);
            return $mydate;
	 }

	 function prepareForSave(&$request, &$responseModel) {
        $type = $responseModel->get('event_type');

            switch ($type) {
              case 1: // single date
                $mydate = $responseModel->get('date_single');
                $this->makeDate($responseModel, $mydate,'`date`');
                $this->makeDate($responseModel, $mydate,'date');
                $type = 1;
                break;
              case 2: // multiple date
                $recurrence = $request->getPostProperty('recurrence');
                $type = $recurrence;    // 2,3,4
                $startdate = $responseModel->get('startdate_input');
                $enddate = $responseModel->get('enddate_input');
                $this->makeDate($responseModel, $startdate,'date');
                $this->makeDate($responseModel, $enddate,'enddate');
                // also monthday, weekday

                break;
              case 5: // monthly
                $type = 5;
                $weekday = $request->getPostProperty('weekday_monthly');
                $responseModel->set('weekday', $weekday );
                // weeknumber, startyear, startmonth, endyear, endmonth
                break;
            }
            $responseModel->set('`type`', $type );
            $responseModel->set('type', $type );


            //prepare author user
            $author_user_id = 0;
            if (Session::isLogin()) {
            	$author_user_id = Session::getUserId();
            }
            if ($author_user_id) $responseModel->set('user_id',$author_user_id);
            if ($author_user_id) $responseModel->set('admin_user_id',$author_user_id);

            $tz =& new MyTimeZone();
            $responseModel->set('date_submitted', gmdate("Y-m-d H:i", $tz->timeNowLocal() ) );
            //print_r( $responseModel );
	 }



     function create(&$source, &$request, &$responseModel) {
     	if ($responseModel->isValid()) {
            require_once WACT_ROOT.'/util/phpcompat/clone.php';

            $this->prepareForSave($request, $responseModel);

            //return 'this';
            $event_id = Event::insertEvent($responseModel);
            if ($event_id) {
            	$responseModel->set('event_id', $event_id);
                $lastRecord = clone_obj($responseModel);


                // Set up the model for adding the next record
                $responseModel->removeAll();
                $responseModel->set('LastRecord', $lastRecord);

                return 'createOK';
                //return 'this';
            } else {
                return 'failure';
            }
        } else {
        }
     }


	 function delete(&$source, &$request, &$responseModel) {
	 	return 'delete';
	 }


     function save(&$source, &$request, &$responseModel) {
        if ($responseModel->isValid()) {
        	$event_id = $request->getParameter('event_id');

        	$this->prepareForSave($request, $responseModel);

            if ($event_id) Event::updateEvent($event_id, $responseModel);
            return 'saveOK';
            //return 'this';
        }
    }

    function clean(&$source, &$request, &$responseModel) {
        $responseModel->removeAll();
        $responseModel->set('supress_errors', 1);
    	return 'cleanOK';
    }

    function back(&$source, &$request, &$responseModel) {
        $responseModel->removeAll();
        $responseModel->set('supress_errors', 1);
    	return 'index';
    }

    // load date
    function loadDate(&$responseModel, $db_property, $wact_property) {
       if ($responseModel->hasProperty($db_property)) {
       		$mydate = $responseModel->get($db_property);
       		//print $date_show;
       		//print strtotime($date_show);
       		$ts = strtotime($mydate);
       		$tz =& new MyTimeZone();
       		$ts = $tz->timeGMT($ts);
       		$day = (integer)gmdate('d',$ts);
       		$month = (integer)gmdate('m',$ts);
       		$year = (integer)gmdate('Y',$ts);
       		$str_date = $day.'/'.$month.'/'.$year;
       		$responseModel->set($wact_property,$str_date);
       		return $str_date;
       }

    }

     function load(&$source, &$request, &$responseModel) {
     	$event_id = $request->getParameter('event_id');
     	//print 'from load: user-id='.$user_id;
     	if ($event_id) {
        	$record =& Event::getRecord($event_id);
        	if (is_null($record)) {
            	return 'notfound';
        	}
            $responseModel->import($record->export());

            $author_show = User::getFullUserName($responseModel);
            $responseModel->set('author_show',$author_show);

            $public_url = Event::getPublicURLByID($event_id);
            $responseModel->set('public_url',$public_url);
            $title = $responseModel->get('event_title');
            $responseModel->set('title',$title);

            $type = $responseModel->get('type');
            switch ($type) {
              case 1:
                $responseModel->set('type1',1);
                $responseModel->set('event_type',1);
                $str = $this->loadDate($responseModel, 'date','date_single');
                $str = $this->loadDate($responseModel, 'date','startdate_input');
                $str = $this->loadDate($responseModel, 'date','enddate_input');

                //print $str;
                break;
              case 2:
                $responseModel->set('type1',2);
                $responseModel->set('event_type',2);
                $responseModel->set('recurrence',2);
                $str = $this->loadDate($responseModel, 'date','startdate_input');
                $str2 = $this->loadDate($responseModel, 'enddate','enddate_input');

                break;
              case 3:
                $responseModel->set('type1',2);
                $responseModel->set('event_type',2);
                $responseModel->set('recurrence',3);
                $str = $this->loadDate($responseModel, 'date','startdate_input');
                $str2 = $this->loadDate($responseModel, 'enddate','enddate_input');
                break;
              case 4:
                $responseModel->set('type1',2);
                $responseModel->set('event_type',2);
                $responseModel->set('recurrence',4);
                $str = $this->loadDate($responseModel, 'date','startdate_input');
                $str2 = $this->loadDate($responseModel, 'enddate','enddate_input');
                break;
              case 5:
                $responseModel->set('type1',5);
                $responseModel->set('event_type',5);
                $weekday = $responseModel->get('weekday');
                $responseModel->set('weekday_monthly',$weekday);
                $responseModel->remove('enddate_input');
                break;
            }

            //print_r( $responseModel );



        }
     }

     //prepare the form view
     function prepare(&$source, &$request, &$responseModel, &$template) {
     	//print 'Prepare form...';
     	if ($this->admin_user) {
     		$responseModel->set('admin_user',1);
     	}
     	if ($this->staff_user) $responseModel->set('staff_user',1);
        $responseModel->set('host',HOST);
        $responseModel->set('app_name',APP_NAME);

        // populate combos
        $monthday =& $template->getChild('monthday');
        $days =& SportDate::getMonthDays();
        $monthday->setChoices($days);

        $weekday =& $template->getChild('weekday');
        $days =& SportDate::getWeekDays();
        $weekday->setChoices($days);
        $weekday_monthly =& $template->getChild('weekday_monthly');
        $weekday_monthly->setChoices($days);

        $weeknumbers =& SportDate::getWeekNumbers();
        $weeknumber =& $template->getChild('weeknumber');
        $weeknumber->setChoices($weeknumbers);

        $startmonth =& $template->getChild('startmonth');
        $endmonth =& $template->getChild('endmonth');
        $months =& SportDate::getMonths();
        $startmonth->setChoices($months);
        $endmonth->setChoices($months);

        $startyear =& $template->getChild('startyear');
        $endyear =& $template->getChild('endyear');
        $years =& SportDate::getYears();
        $startyear->setChoices($years);
        $endyear->setChoices($years);

        return;

     }

}

?>